//
//  KRAlbumInfoController.m
//  cookBook
//
//  Created by kuroken on 16/1/21.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRAlbumInfoController.h"
#import <SVProgressHUD.h>
#import <MJExtension.h>
#import <MJRefresh.h>
#import <UITableView+FDTemplateLayoutCell.h>
#import "KRHttpRecipeTool.h"
#import "KRConst.h"
#import "KRAlbumInfo.h"
#import "KRAlbumInfoCell.h"
#import "KRAlbumInfoListCell.h"
#import "KRRecipeInfoController.h"
#import "KRAlbumInfoList.h"
#import "KRNoNetCell.h"

@interface KRAlbumInfoController ()
@property (nonatomic, strong) KRAlbumInfo *albumInfo;
@property (nonatomic, assign) NSUInteger offset;
/** 当前请求 */
@property (nonatomic, weak) NSURLSessionDataTask *currentDataTask;
@property (nonatomic, assign, getter=isError) BOOL error;
@end

@implementation KRAlbumInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerClass:[KRAlbumInfoCell class] forCellReuseIdentifier:@"albumInfo"];
    [self.tableView registerClass:[KRAlbumInfoListCell class] forCellReuseIdentifier:@"albumInfoList"];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    /* 加载数据 */
    [self loadData];
        
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!self.albumInfo) {
        // 显示指示器
        [SVProgressHUD show];
        self.tableView.userInteractionEnabled = NO;
        self.tableView.scrollEnabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.currentDataTask cancel];
    self.currentDataTask = nil;
    [SVProgressHUD dismiss];
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
}

/**
 *  上拉刷新控件
 */
- (void)setupFooterRefresh
{
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"没有更多数据" forState:MJRefreshStateNoMoreData];
    self.tableView.mj_footer = footer;
}


- (void)loadData
{    
    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRInfoGetAlbumInfo;
        requestParams[@"aid"] = self.albumID;
        requestParams[@"limit"] = @"10"; // 获取多少条数据
        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset]; // 定位开始位置
    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;

        // 上拉刷新控件
        [self setupFooterRefresh];
        
        self.error = NO;
        self.tableView.scrollEnabled = YES;
        
        self.albumInfo = [KRAlbumInfo mj_objectWithKeyValues:json[@"result"]];
        
        self.offset += 10;
        if (self.offset > [self.albumInfo.recipeCount integerValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            self.offset = [self.albumInfo.recipeCount integerValue];
        }
        
        [self.tableView reloadData];
        
        // 移除蒙板
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;
        self.error = YES;
        [self.tableView reloadData];
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD showErrorWithStatus:@"网络繁忙"];
        });
        
        KRLog(@"%@, %@", self, error);
    }];
}

- (void)loadMoreData
{
    KRLog(@"从第%d个菜谱开始加载", (int)self.offset);

    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRInfoGetAlbumInfo;
        requestParams[@"aid"] = self.albumID;
        requestParams[@"limit"] = @"10";
        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset];
    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;
        
        KRAlbumInfo *albumInfo = [KRAlbumInfo mj_objectWithKeyValues:json[@"result"]];
        NSArray *albumInfoListArray = albumInfo.albumInfoListArray;
        [self.albumInfo.albumInfoListArray addObjectsFromArray:albumInfoListArray];
        
        self.offset += 10;
        if (self.offset >= [self.albumInfo.recipeCount integerValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        [self.tableView reloadData];
        
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        [SVProgressHUD showErrorWithStatus:@"网络繁忙！"];

        KRLog(@"%@, %@", self, error);
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.isError) return 1; // 请求失败
    if (!self.albumInfo) return 0;
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.isError) return 1; // 请求失败
    if (section == 0) {
        return 1;
    } else if (section == 1){
        return self.albumInfo.albumInfoListArray.count;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isError) {
        KRNoNetCell *cell = [KRNoNetCell cellWithTableView:tableView];
        [cell setNoNetHint:@"请求超时"];
        return cell;
    }

    if (indexPath.section == 0) {
        KRAlbumInfoCell *cell = [KRAlbumInfoCell cellWithTableView:tableView];
        cell.albumInfo = self.albumInfo;
        return cell;
    } else if (indexPath.section == 1){
        KRAlbumInfoListCell *cell = [KRAlbumInfoListCell cellWithTableView:tableView];
        cell.infoList = self.albumInfo.albumInfoListArray[indexPath.row];
        return cell;
    }
    
    return nil;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) return [UIScreen mainScreen].bounds.size.height - KRTopBarHeight;

    if (indexPath.section == 0) {
        return [tableView fd_heightForCellWithIdentifier:@"albumInfo" cacheByIndexPath:indexPath configuration:^(KRAlbumInfoCell *cell) {
            cell.albumInfo = self.albumInfo;
        }];
    } else if (indexPath.section == 1) {
        return [tableView fd_heightForCellWithIdentifier:@"albumInfoList" cacheByIndexPath:indexPath configuration:^(KRAlbumInfoListCell *cell) {
            cell.infoList = self.albumInfo.albumInfoListArray[indexPath.row];
        }];
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) {
        self.error = NO;
        [self.tableView reloadData];
        [self loadData];
        return;
    }
    
    if (indexPath.section == 0) return;

    KRRecipeInfoController *infoVc = [[KRRecipeInfoController alloc] init];
    infoVc.recipeID = self.albumInfo.albumInfoListArray[indexPath.row].list_recipeID; // RecipeId
    
    [self.navigationController pushViewController:infoVc animated:YES];
}

@end